import React from 'react';
import { Button, Form, Input } from 'antd';
import './DeptForm.css';

// DeptForm 组件用于创建和编辑部门信息的表单
class DeptForm extends React.Component {
  constructor(props) {
    super(props);
    this.formRef = React.createRef();
  }

  componentDidMount() {
    // 当组件挂载后，如果处于编辑模式，则设置表单的初始值
    if (this.props.editData) {
      this.formRef.current.setFieldsValue(this.props.editData);
    }
  }

  onFinish = (values) => {
    // 判断当前是编辑模式还是新增模式
    if (this.props.editData) {
      // 编辑模式：合并旧值和新值
      let oldValues = this.props.editData;
      for (let item in values) {
        oldValues[item] = values[item];
      }

      const url = 'http://1.94.134.166:8805/dept';
      const config = {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          Authorization: localStorage.getItem('Authorization'),
        },
        body: JSON.stringify(oldValues),
      };

      fetch(url, config)
        .then((response) => response.json())
        .then((res) => {
          this.props.refreshList();
          this.props.closeDrawer();
        });
    } else {
      // 新增模式
      values.parentId = 0;
      const url = 'http://1.94.134.166:8805/dept';
      const config = {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: localStorage.getItem('Authorization'),
        },
        body: JSON.stringify(values),
      };

      fetch(url, config)
        .then((response) => response.json())
        .then((res) => {
          this.props.refreshList();
          this.props.closeDrawer();
        });
    }
  };

  render() {
    const { editData={} } = this.props;     // 从props中解构出editData
    const title = editData ? '编辑部门' : '新增部门';     // 根据editData设置表单标题

    return (
      // 渲染表单组件
      <>
        <div className="deptForm_title">{title}</div>
        <div className="deptForm_inputarea">
          <Form
            name="basic"
            wrapperCol={{ span: 24 }}
            initialValues={{}}
            onFinish={this.onFinish}
            ref={this.formRef}
          >
            <Form.Item
              className="deptName"
              name="deptName"
              label="部门名称"
              rules={[
                { required: true, message: '请输入部门名称!' },
                {
                  pattern: /^[a-zA-Z0-9_\u4e00-\u9fa5]{2,20}$/,
                  message:
                    '部门名称只能包含中文、字母、数字和下划线，且长度为2到20个字符',
                },
              ]}
            >
              <Input
                size="large"
                placeholder="请输入部门名称"
                className="input_deptName"
              />
            </Form.Item>

            <Form.Item
              name="deptPy"
              label="部门拼音"
              rules={[
                { required: true, message: '请输入部门拼音!' },
                {
                  pattern: /^[a-zA-Z]{2,20}$/,
                  message: '部门拼音只能包含字母，且长度为2到20个字符',
                },
              ]}
            >
              <Input
                size="large"
                placeholder="请输入部门拼音"
                className="input_deptPy"
              />
            </Form.Item>

            <Form.Item
              name="phone"
              label="联系方式"
              rules={[
                {required: true, message: '请输入部门联系方式!'},
                {pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确'},
              ]}
            >
              <Input
                size="large"
                placeholder="请输入部门联系方式"
                className="input_deptPhone"
              />
            </Form.Item>

            <Form.Item wrapperCol={{span: 24}}>
              <Button type="primary" htmlType="submit" className="deptForm_submit">
                提交
              </Button>
            </Form.Item>
          </Form>
        </div>
      </>
    );
  }
}

export default DeptForm;
